package com.example.transaction.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.entity.Item;
import com.example.transaction.sys.entity.LoginLog;
import com.example.transaction.sys.entity.Order;
import com.example.transaction.sys.entity.User;
import com.example.transaction.sys.service.ILoginLogService;
import com.example.transaction.sys.service.IUserService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zh
 * @since 2023-06-20
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private LoginLogController loginLogController;

    /**
     * 查询全部用户
     * @return
     */
    @Cacheable(value = "users", key = "'allusers'")
    @GetMapping("/all")
    public Result<List<User>> getAllUser(){
        List<User>list=userService.list();
        return Result.success(list,"查询成功");
    }

    /**
     * 登录接口
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result<Map<String,Object>>login(@RequestBody User user, HttpServletRequest request){
        Map<String,Object>data=userService.login(user);
//        if(data!=null){
//            return Result.success(data);
//        }
        if (data != null) {
            // 登录成功，调用新增登录日志接口
            // 获取IP地址
            String ipAddress = request.getRemoteAddr();

            // 获取操作系统和浏览器信息
            String userAgent = request.getHeader("User-Agent");
            String operatingSystem = extractOperatingSystem(userAgent);
            String browser = extractBrowser(userAgent);

            // 登录成功后新增登录日志
            LoginLog loginLog=new LoginLog();
            loginLog.setUserID((Integer) userService.getUserInfo((String)data.get("token")).get("userID"));
            loginLog.setIp(ipAddress);
            loginLog.setOs(operatingSystem);
            loginLog.setBrowser(browser);
            loginLogController.addLoginLog(loginLog);
            return Result.success(data);
        }
        return Result.fail(20002,"用户名或密码错误");
    }

    // 提取操作系统和浏览器信息

    private String extractOperatingSystem(String userAgentString) {
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
        return userAgent.getOperatingSystem().getName();
    }

    private String extractBrowser(String userAgentString) {
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
        return userAgent.getBrowser().getName();
    }


    /**
     * 获取用户信息接口
     * @param token
     * @return
     */
    @Cacheable(value = "users", key = "#token")
    @GetMapping("/info")
    public Result<Map<String,Object>>getUserInfo(@RequestParam("token")String token){
        //根据token来获取用户信息，从redis获取
        Map<String,Object>data=userService.getUserInfo(token);
        if(data!=null){
            return Result.success(data);
        }
        return Result.fail(20003,"登录信息超时，请重新登录");
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @PostMapping("/logout")
    public Result<?>logout(@RequestHeader("token")String token){
        userService.logout(token);
        return Result.success();
    }

    /**
     * 查询所有用户，或者按条件查询（管理员可用
     * @param username
     * @param phoneNumber
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Cacheable(value = "users", key = "'allusers'+#username+#phoneNumber+#pageNo+#pageSize")
    @GetMapping("/list")
    public Result<Map<String,Object>>getUserList(@RequestParam(value = "username",required = false)String username,
                                             @RequestParam(value = "phoneNumber",required = false)String phoneNumber,
                                             @RequestParam(value = "pageNo")Long pageNo,
                                             @RequestParam(value = "pageSize")Long pageSize){
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(username),User::getUsername,username);     //模糊查询
        wrapper.like(StringUtils.hasLength(phoneNumber),User::getPhoneNumber,phoneNumber);
        wrapper.eq(User::getUserType,"普通用户");
        Page<User> page=new Page<>(pageNo,pageSize);
        userService.page(page,wrapper);
        Map<String,Object>data=new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return Result.success(data);
    }

    /**
     * 注册接口
     * @param user
     * @return
     */
    @PostMapping("/register")
    @CacheEvict(value = "users", allEntries = true)
    public Result<?>addUser(@RequestBody User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        try {
            userService.save(user);
        }catch (Exception e){
            return Result.fail("用户名已经存在");
        }
        return Result.success("新增用户成功");
    }

    /**
     *
     * @param userID
     * @param avatar
     * @return
     */
    @CacheEvict(value = "users", allEntries = true)
    @PutMapping("/updateAvatarByID")
    public Result<?> updateAvatar(@RequestParam("userID") Long userID, @RequestParam("avatar") String avatar) {
        try {
            User user = userService.getById(userID);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            user.setAvatar(avatar);
            userService.updateById(user);
        } catch (Exception e) {
            return Result.fail("更新头像失败");
        }
        return Result.success("更新头像成功");
    }

    /**
     * 根据用户id更新用户
     * @param user
     * @return
     */
    @CacheEvict(value = "users", allEntries = true)
    @PutMapping("/updateByID")
    public Result<?>updateUser(@RequestBody User user){
        user.setPassword(null);
        try {
            userService.updateById(user);
        }catch (Exception e){
            return Result.fail("用户名已经存在");
        }
        return Result.success("修改用户成功");
    }

    /**
     * 根据用户id查找信息
     * @param id
     * @return
     */
    @Cacheable(value = "users", key = "#id")
    @GetMapping("/{id}")
    public Result<User>getUserById(@PathVariable("id")Integer id){
        User user=userService.getById(id);
        return Result.success(user);
    }

    /**
     * 根据username查找对应的userid
     * @param username
     * @return
     */
    @Cacheable(value = "users", key = "#username")
    @GetMapping("/username/{username}")
    public Result<List<Integer>>getUserIdsByUsername(@PathVariable("username")String username){
        List<Integer>lists=userService.getUserIdsByUsername(username);
        return Result.success(lists);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @CacheEvict(value = "users", allEntries = true)
    @DeleteMapping("/{id}")
    public Result<User>deleteUserById(@PathVariable("id")Integer id){
        userService.removeById(id);
        return Result.success("删除用户成功");
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @CacheEvict(value = "users", allEntries = true)
    @PutMapping("/change")
    public Result<?>changePassword(@RequestBody User user,
                                   @RequestParam("currentPassword")String currentPassword,
                                   @RequestParam("newPassword")String newPassword){
        if(userService.changePassword(user,currentPassword,newPassword)) return Result.success("修改密码成功");
        return Result.fail("修改失败");
    }

    /**
     * 修改用户信息
     * @return
     */
    @CacheEvict(value = "users", allEntries = true)
    @PutMapping("/updateUser/{id}")
    public Result<Item> updateItem(@PathVariable("id") Integer id,
                                   @RequestParam(value = "phoneNumber") String phoneNumber,
                                   @RequestParam(value = "email") String email){
        User user=new User();
        user.setUserID(id);
        user.setPhoneNumber(phoneNumber);
        user.setEmail(email);
        userService.updateById(user);
        return Result.success("更新用户信息成功");
    }


    /**
     * 查询传入日期（及前五天）的注册的用户,当天有就返回数量，没有就返回0
     * @param date
     * @return
     */
    @Cacheable(value = "users", key = "#date")
    @GetMapping("/registerNumber")
    public Map<LocalDate, Long> getRegisterNumber(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Map<LocalDate, Long> registerNumberByDate = new TreeMap<>();

        for (int i = 0; i < 6; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            QueryWrapper<User> userWrapper = new QueryWrapper<>();
            userWrapper.apply("DATE(registration_time) = {0}", formattedDate);
            Long registerNumber = userService.count(userWrapper);

            registerNumberByDate.put(currentDate, registerNumber);
        }

        return registerNumberByDate;
    }

}
